//
//  UIImage+JXE.swift
//  JXUtilsDemo
//
//  Created by ccks on 2018/11/28.
//  Copyright © 2018 Zhu Jinxin. All rights reserved.
//

import Foundation
import UIKit

extension JX_TypeWrapper where T : UIImage {
    
    static func convertViewToImage(view:UIView) -> UIImage {
        
        let size = view.bounds.size
        
        UIGraphicsBeginImageContextWithOptions(size, true, UIScreen.main.scale)
        
        view.layer.render(in: UIGraphicsGetCurrentContext()!)
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        UIGraphicsEndImageContext()
        
        return image!
        
    }
    
    //渲染Image颜色
    func image(withTintColor tintColor: UIColor?) -> UIImage? {
        //We want to keep alpha, set opaque to NO; Use 0.0f for scale to use the scale factor of the device’s main screen.
        UIGraphicsBeginImageContextWithOptions(SELF.size, _: false, _: 0.0)
        tintColor?.setFill()
        let bounds = CGRect(x: 0, y: 0, width: SELF.size.width, height: SELF.size.height)
        UIRectFill(bounds)
        //Draw the tinted image in context
        SELF.draw(in: bounds, blendMode: .destinationIn, alpha: 1.0)
        let tintedImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return tintedImage
    }
    
    
}

extension JX_TypeWrapper where T : CIImage {
    
    func createClearImage(_ image : CIImage, width : CGFloat ) -> UIImage? {
        
        // 1.调整小数像素到整数像素,将origin下调(12.*->12),size上调(11.*->12)
        let extent = image.extent.integral
        
        // 2.将指定的大小与宽度和高度进行对比,获取最小的比值
        let scale = min(width / extent.width, width/extent.height)
        
        // 3.将图片放大到指定比例
        let width = extent.width * scale
        let height = extent.height * scale
        // 3.1创建依赖于设备的灰度颜色通道
        let cs = CGColorSpaceCreateDeviceGray();
        // 3.2创建位图上下文
        let bitmapRef = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: cs, bitmapInfo: 0)
        
        // 4.创建上下文
        let context = CIContext(options: nil)
        
        // 5.将CIImage转为CGImage
        let bitmapImage = context.createCGImage(image, from: extent)
        
        // 6.设置上下文渲染等级
        bitmapRef!.interpolationQuality = .none
        
        // 7.改变上下文的缩放
        bitmapRef?.scaleBy(x: scale, y: scale)
        
        // 8.绘制一张图片在位图上下文中
        bitmapRef?.draw(bitmapImage!, in: extent)
        
        // 9.从位图上下文中取出图片(CGImage)
        guard let scaledImage = bitmapRef?.makeImage() else {return nil}
        
        // 10.将CGImage转为UIImage并返回
        return UIImage(cgImage: scaledImage)
    }
    
    
}
